Skip to content

Fix cache-miss diagnostic for undefined keys - #863

Open
LukasMod wants to merge 1 commit into
Expensify:mainfrom
callstack-internal:fix/cache-miss-diagnostic-followups
Open

LukasMod wants to merge 1 commit into
Expensify:mainfrom
callstack-internal:fix/cache-miss-diagnostic-followups

Conversation

@LukasMod

@LukasMod LukasMod commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Details

Follow-ups to #850 from the review of Expensify/App#102135 (Expensify/App#102135 (review)).

getState(undefined) now throws. Checking cache.getAllKeys().has(key) first in reportCacheMissIfStorageHasValue fixes it.

  • getState(undefined) no longer throws. The cache-miss check now tests the key index before isRamOnlyKey, whose string parsing crashed on a non-string key. Restores the pre-3.0.119 contract: unknown or non-string key returns undefined. Behavioral, covered by tests/unit/OnyxSubscriptionManagerTest.ts "should return undefined without throwing for an undefined key".

The cache-miss check marks a collection as reported before storage confirms the miss, and never re-checks the cache afterwards.

  • Partially fixed, after the storage read, a value already back in the cache means no miss, so no hmmm. Covered by "should not report when the value reached the cache before storage answered". The early per-collection mark stays on purpose. It caps storage at one read per collection per session, and the miss branch runs on every render of a subscriber whose key is missing from the cache, so it has to stay at a few Set lookups. The price is that a first member with empty storage hides a later real miss in that collection for the session. One hmmm per collection already tells us where to look, and a real miss means storage holds a value the cache lost, which no Onyx write path produces. Better missing that over adding reads to the render path. I would keep as it is and observe logs.

?? undefined in get/multiGet is dead code.

  • Onyx.get and Onyx.multiGet drop a ?? undefined that could never fire. The cache never stores null, so the read returns the same values as before. Mechanical, covered by tests/unit/onyxTest.ts describe('get') and describe('multiGet') missing-key cases.

Related Issues

Expensify/App#101910

Follow up after review Expensify/App#102135 (review)

Linked E/App PR

Expensify/App#104992

Automated Tests

Manual Tests

Test 1: Smoke, normal use produces no cache-miss logs

  1. Sign in on tab A and tab B.
  2. In tab A open a chat, type a draft, send a message, open a second chat.
  3. Sign out in tab A, then sign back in.
  4. Confirm tab B shows no [Onyx] Cache held no value for a key storage still has line and no [Onyx] Could not check storage line in the console.
  5. Confirm both tabs still render chats and the sent message after sign-in.

Test 2: Undefined key resolves instead of alerting

  1. In tab A's console run await Onyx.get() with no argument.
  2. Confirm it resolves undefined.
  3. Confirm no [alrt] Unhandled Promise Rejection line and no TypeError mentioning lastIndexOf appears. On 3.0.119 to 3.0.123 both appear.
  4. Run await Onyx.multiGet([undefined]) and confirm it resolves [undefined].

Author Checklist

  • I linked the correct issue in the ### Related Issues section above
  • I linked the corresponding Expensify/App PR in the ### Linked E/App PR section above, and verified this change against it (E/App CI passed and manual testing completed)
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android / native
    • Android / Chrome
    • iOS / native
    • iOS / Safari
    • MacOS / Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified that proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.js or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • If we are not using the full Onyx data that we loaded, I've added the proper selector in order to ensure the component only re-renders when the data it is using changes
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR author checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari
web.test.1.mov
web 2

@LukasMod
LukasMod force-pushed the fix/cache-miss-diagnostic-followups branch from 52dbb61 to 7903090 Compare October 26, 2026 11:10
@LukasMod LukasMod changed the title Fix cache-miss diagnostic for undefined keys, unconfirmed misses and concurrent writes Fix cache-miss diagnostic for undefined keys Oct 26, 2026
@LukasMod

Copy link
Copy Markdown
Contributor Author

@fabioh8010
Could you take a look at this one? These are small follow-ups from the Onyx.get review:

  • a dead ?? undefined cleanup after get/multiGet moved to getState
  • a guard reorder so getState(undefined) returns undefined instead of throwing in lastIndexOf (defensive, keys are already typed as OnyxKey)
  • a cache re-check before the cache-miss hmmm so a write that lands during the storage read is not logged as a miss

cc @TaduJR

@LukasMod
LukasMod marked this pull request as ready for review October 26, 2026 12:10
@LukasMod
LukasMod requested a review from a team as a code owner October 26, 2026 12:10
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T20:23:25.655517Z 7903090 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@melvin-bot
melvin-bot Bot requested review from chuckdries and removed request for a team October 26, 2026 12:11
@LukasMod

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@fabioh8010

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 79030906b4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@TaduJR

TaduJR commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

Assignment here @chuckdries

Thanks.

Reviewing...

@chuckdries
chuckdries requested a review from TaduJR October 28, 2026 13:53

@TaduJR TaduJR left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @LukasMod. Checking the key index first and removing ?? undefined both look good.

Blocking: Double checked my previous comment and the re-check at :34, hides the data loss this log is for. Details inline.

The description's "first member with empty storage" case is common on web. A removal in another tab reaches the sync handler as undefined, and cache.set(key, undefined) keeps the key indexed but clears its nullish mark, so it looks like a lost value. Its next re-read mutes the collection, and if that tab sets the key again first, it logs a false alarm the re-check misses.

Marking the key nullish when cache.set gets null/undefined fixes both and keeps the key indexed, so clear still removes it. Dropping it from the index instead would leave it in storage after sign-out when a stale sync read lands after a local write. This was already in #850, so a follow-up is fine:

// OnyxCache.set
if (value === null || value === undefined) {
    this.nullishStorageKeys.add(key);
    delete this.storageMap[key];
    // ...
}
this.nullishStorageKeys.delete(key);


function reportCacheMissIfStorageHasValue(key: OnyxKey): void {
if (OnyxKeys.isRamOnlyKey(key) || !cache.getAllKeys().has(key) || cache.hasNullishStorageKey(key)) {
if (!cache.getAllKeys().has(key) || OnyxKeys.isRamOnlyKey(key) || cache.hasNullishStorageKey(key)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only works while undefined isn't in the key index. Onyx.set(undefined, 1) adds it before it throws, and after that getState(undefined) throws for every reader. It also returns the value of a key named 'undefined'. Checking the key where it enters Onyx, as update does, fixes both:

// OnyxKeys.ts
function isValidKey(key: unknown): key is string {
    return typeof key === 'string';
}

// Top of Onyx.set and Onyx.merge
if (!OnyxKeys.isValidKey(key)) {
    Logger.logInfo(`Invalid ${typeof key} key provided in Onyx set. Key must be of type string. Skipping this operation.`);
    return Promise.resolve();
}

// Top of getState, which every read goes through
if (!OnyxKeys.isValidKey(key)) {
    return undefined as OnyxValue<TKey>;
}

Storage.getItem(key)
.then((value) => {
if (value === undefined || value === null) {
if (value === undefined || value === null || cache.get(key) !== undefined) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This skips the log when a write lands on a lost value. The cache has lost {a, b}, and merge(key, {c: 3}) builds on the empty cache. On web it overwrites storage, so the read sees {c: 3} in the cache and nothing is logged.

Suggested change
if (value === undefined || value === null || cache.get(key) !== undefined) {
if (value === undefined || value === null) {

Comment on lines +404 to +413
it('should not report when the value reached the cache before storage answered', async () => {
await StorageMock.setItem(ONYXKEYS.TEST_KEY, 'from-storage');
forgetValueButKeepKey(ONYXKEYS.TEST_KEY);

onyxSubscriptionManager.getState(ONYXKEYS.TEST_KEY);
cache.set(ONYXKEYS.TEST_KEY, 'from-storage');
await waitForPromisesToResolve();

expect(logHmmmSpy).not.toHaveBeenCalled();
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test pins the re-check. I'd replace it with the merge case, which fails on 79030906. It needs import createDeferredTask from '../../lib/createDeferredTask';.

Suggested change
it('should not report when the value reached the cache before storage answered', async () => {
await StorageMock.setItem(ONYXKEYS.TEST_KEY, 'from-storage');
forgetValueButKeepKey(ONYXKEYS.TEST_KEY);
onyxSubscriptionManager.getState(ONYXKEYS.TEST_KEY);
cache.set(ONYXKEYS.TEST_KEY, 'from-storage');
await waitForPromisesToResolve();
expect(logHmmmSpy).not.toHaveBeenCalled();
});
it('should report when a merge lands on the lost value before storage answers', async () => {
await StorageMock.setItem(ONYXKEYS.TEST_KEY, {a: 1, b: 2});
forgetValueButKeepKey(ONYXKEYS.TEST_KEY);
const getItemMock = StorageMock.getItem as jest.Mock;
const readStorage = getItemMock.getMockImplementation() as (key: OnyxKey) => Promise<unknown>;
const storageAnswer = createDeferredTask();
getItemMock.mockImplementationOnce((key: OnyxKey) => {
const storedValue = readStorage(key);
return storageAnswer.promise.then(() => storedValue);
});
onyxSubscriptionManager.getState(ONYXKEYS.TEST_KEY);
await Onyx.merge(ONYXKEYS.TEST_KEY, {c: 3});
storageAnswer.resolve();
await waitForPromisesToResolve();
expect(cache.get(ONYXKEYS.TEST_KEY)).toEqual({c: 3});
expect(logHmmmSpy).toHaveBeenCalledTimes(1);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants